-- RewardOpenCardView
local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.RewardDrawPanel_Scene_card

local ShakeConfig = require("app.configs.ShakeConfig")
local BoxRender = require("app.reward.views.renders.BoxRender")							
local Armature = app:getClass("Armature")

local Reward_Max_Count = 5
local Max_Quality_Count = 5
local Color_String = "activityCardColor%d"
local Card_Image_Path = "art/activity_icon/welfare_card_0%d.png"
local Card_Open_Light_Path = "art/activity_icon/CardLight_0%d.png"

local string_format = string.format

local QualityColor = {
    cc.c3b(176, 176, 176), --白色
    cc.c3b(117, 211, 124),  --绿色
    cc.c3b(108, 158, 239),  --蓝色
    cc.c3b(190, 76, 255),  --紫色
    cc.c3b(255, 154, 55),   --橙色
}

function ClassRef:init()
	self._ui["Panel/Image_73"]:setContentSize(display.size)
	self._num = self._ui["Panel/Panel_open/num"]
	self._tips = self._ui["Panel/tips"]
	self._card = self._ui["Panel/card"]
	self._card:findChild("Panel/tips_0"):setVisible(false)
	self._card:findChild("Panel/Panel_lock"):setVisible(false)
	self._card_ImageS = self._card:findChild("Panel/Image_s")
    self._card_ImageBack = self._card:findChild("Panel/img_back")
	self._buttonPanel = self._ui["Panel/Panel_open"]		
	self.state = 0

    -- 循环播放抖动
    self._card:getTimeline():play("float", true)
	
	self._ui.Button:addClickEventListener(function()
		if not self._data then return end
		self.state = self.state + 1		
		if self.state == 1 then
			local money = UD:getGold()
			if money < self._data.needGold then
				display.pushToast(L("lua_code_text_400"))
				self.state = 0
				return 
			end
			
			executeFunc(self._onOperate, "openMiraculousCard", {})	
			-- 开启延迟
			app:sendMsg("PlayerController", "setGetExpEnable", false)				
			UD.player:setApplyEnable(false)
			UD.bag:setApplyEnable(false)
			display.setToastEnable(false)	
			
			self:setButtonVisible(false)									
			--self:playCardRollEffect()
		elseif self.state == 2 then
			self:openCard()
		end			
	end)
	
	display.uiAddClick(self._ui["Panel"], function()
		if self.state == 0 then
            self:playCloseViewEffect(self._tag)
		end
	end)	
end

function ClassRef:show()
	self:setVisible(true)
	self._card:setVisible(true)
	self._buttonPanel:setVisible(true)
	self.state = 0
end

function ClassRef:setData(data)
	self._data = data
	self:refresh()
end

function ClassRef:setTag(tag)
	self._tag = tag
end

function ClassRef:refresh()
	if not self._data then return end
	if cc.isDead(self._num) then return end
	local data = self._data
	local money = UD:getGold()
	if money < data.needGold then
		self._num:setColor(cc.c3b(255, 105, 85))
	else
		self._num:setColor(cc.c3b(255, 255, 255))
	end
	self._tips:setVisible(true)
	self._num:setString(data.needGold)
	self._num:setVisible(true)
	self._tips:setString(string.format(L("activityCardTips3"), data.nowCof))

	-- 剩余次数
	if data.remainFreeCount and data.remainFreeCount > 0 then
		self._ui.tips_time:setVisible(true)
		self._ui.tips_time:setString(string_format(L("activityCardTips7"), data.remainFreeCount))
	else
		self._ui.tips_time:setVisible(false)
	end

	if not data.quality then return end
	local quality = data.quality
	if quality <= Max_Quality_Count then
		local path = string_format(L(Card_Image_Path), quality)
		self._card_ImageS:loadTexture(path)
		local tempStr = string_format(Color_String, quality)
		self._card:findChild("Panel/Panel_card/text"):setString(string_format(L("activityCardTips4"), L(tempStr)))

		path = string_format(L(Card_Open_Light_Path), quality)
		self._card:findChild("Panel/light"):setTexture(path)
		self._card:findChild("Panel/newwar_light_big2_1"):setTexture(path)
	end
	-- 抽卡收到服务器消息返回消息之后再开始播放翻转动画
	if self.state == 1 then
		self:playCardRollEffect()
	end
end

function ClassRef:onOperate(cb)
	self._onOperate = cb
end

function ClassRef:openCard()
	self._card:setVisible(false)		
	self._buttonPanel:setVisible(false)	
	
	local bg = ccui.ImageView:create(Res.BoxBg)
	bg:ignoreContentAdaptWithSize(false)
	bg:setContentSize(display.size)
	bg:setPosition(display.cx, display.cy)
	self:addChild(bg)
	
	self._root:removeFromParent()
	self._root, self._uiBinding = cc.CSLoader:createNode(Res.BoxOpenScene, true, true, true)
	self._root:setContentSize(display.width, display.height)
	self._root:setAnchorPoint(0.5, 0.5)
	self._root:setPosition(display.width/2, display.height/2)
	display.setAutoScale(self._root)
	ccui.Helper:doLayout(self._root)
	
	self._root:setName(self:getViewName())
	self._ui = display.uiDelegate(self._root)
	self:addChild(self._root, 1)
	
	for i = 1, Reward_Max_Count do
		-- 资源里一共有5个panel，只显示第三个
		if i ~= 3 then
			local panel = self._ui["Panel/Panel_" .. i]
			panel:setVisible(false)
			
			local panel_open = self._ui["Panel/Panel_open_" .. i]
			panel_open:setVisible(false)
        else
            local panel = self._ui["Panel/Panel_" .. i]
            display.uiAddClick(panel, function()
                self:_openAllCard()
            end)
		end
	end	
	
	self._ui.Button:addClickEventListener(function()
		self:_openAllCard()
	end)

    -- 省略最后一步
	self:_openAllCard()

    -- 未打开的特效
    self:setUnOpenArmature()
end

function ClassRef:setUnOpenArmature()
    local panel = self._ui.Panel
    local params = {
        armatureName = "kbx_xhg",
        path = "armatures/effect/kbx_xhg"
    }
    local armature = Armature.create(params)
    local size = panel:getContentSize()
    armature:setPosition(size.width/2, size.height/2)
    panel:addChild(armature, -1)
    armature:gotoAndPlay("kbx_xhg", math.random())

    armature:setColor(QualityColor[self._data.quality])
end

function ClassRef:_openAllCard()
    if not self._data then return end
	local conf = ShakeConfig:getConfig(11)
	display.nodeShake(self, conf)

	self._ui.Button:setVisible(false)
	local panel_3 = self._ui["Panel/Panel_3"] 
	panel_3:setVisible(false)
	
    local panel = self._ui.Panel
	local posX = panel_3:getPositionX()
	local posY = panel_3:getPositionY()
    local quality = self._data.quality or 1
	
	local params = {
        armatureName = "kbx_zkdh",
        path = "armatures/effect/kbx_zkdh"
    }
    local armBg = Armature.create(params)
	armBg:setPosition(posX, posY)
	panel:addChild(armBg, 1)
	
    local ani = {
		name = "kbx_zkdh",
		playTimes = 1,
		completeCallback = function()
		local action = cc.FadeIn:create(5/24)
		local panel_open_3 = self._ui["Panel/Panel_open_3"]
		panel_open_3:setVisible(true)
		panel_open_3:setOpacity(0)
		panel_open_3:runAction(action)
	end}
	armBg:playAni(ani)

    -- 根据品质替换不同底板
    if quality > 1 then
        local fileName = "kbx_bg" .. quality
        local params = {
            armatureName = "dh/bg1",
            path = "armatures/effect/" .. fileName
        }
        local arm1 = Armature.create(params)
        armBg:setSlotArmature("xbnxdf", arm1)

        local params = {
            armatureName = "dh/bg2",
            path = "armatures/effect/" .. fileName
        }
        local arm2 = Armature.create(params)
        armBg:setSlotArmature("xbzsd", arm2)
    end

    -- 上层特效
    local params = {
        armatureName = "kbx_zktx",
        path = "armatures/effect/kbx_zktx"
    }
    local armFg = Armature.create(params)
    armFg:setPosition(posX, posY)
    panel:addChild(armFg, 3)
    local ani = {
        name = "kbx_zktx",
        playTimes = 1,
        completeCallback = function(sender)
            sender:removeFromParent()
            self:_openBoxOver()
        end
    }
    armFg:playAni(ani)

    if quality > 1 then
        armFg:setColor(QualityColor[quality])
    end

    -- setData
	local panel_open_3 = self._ui["Panel/Panel_open_3"] 
	if panel_open_3 then
		local render = BoxRender.create(nil, panel_open_3)
        render:setLocalZOrder(2)
		render:setData(self._data)
	end 
end

function ClassRef:_openBoxOver()
    self._ui.tips:setVisible(true)
    self._root:getTimeline():gotoFrameAndPlay(0, true)

    display.uiAddClick(self._ui.Panel, function()
        executeFunc(self._onOperate, "getMiraculousCardInfo", {self._data.uuid})
        self:closeView()

        -- 关闭延迟
        UD.player:setApplyEnable(true)
        UD.bag:setApplyEnable(true)
        display.setToastEnable(true)
        app:sendMsg("PlayerController", "setGetExpEnable", true)
    end)
end

function ClassRef:playCardRollEffect()
    local timeline = self._card:getTimeline()
	timeline:setLastFrameCallFunc(function()
			self._card_ImageS:setVisible(true)
			self._buttonPanel:setVisible(true)
			self._ui["Panel/Panel_open/Text_name_1"]:setVisible(true)
		    self._tips:setVisible(false)
            self._ui["Panel/Panel_open/num"]:setVisible(false)
            self._ui.tips_time:setVisible(false)
	end)
    timeline:play("light", false)
end

function ClassRef:playCloseViewEffect(idx)
	if not idx then
		self:closeView()
		return
	end

    self._ui.Image_73:setVisible(false)
    self._ui.Panel_open:setVisible(false)
    self._ui.tips:setVisible(false)

    local scaleTo = self._data.cardScale[idx]
    local posTo = self._data.cardPositon[idx]

    local Action_1 = cc.ScaleTo:create(0.333, scaleTo)
    local Action_2 = cc.MoveTo:create(0.333, posTo)
    -- 卡牌翻转动画
    -- 持续时间、半径初始值、半径增量、仰角初始值、仰角增量、离x轴的偏移角、离x轴的偏移角的增量
    local Action_3 = cc.OrbitCamera:create(0.333, 10, 0, 0, -360, 0, 0)
    local Actions_1 = cc.Spawn:create(Action_1, Action_2, Action_3)
    local Actions_2 = cc.CallFunc:create(function()
        self:closeView()
    end)
    local actions = cc.Sequence:create(Actions_1, Actions_2)
    self._card:runAction(actions)
	AM.playSoundById(2231)
end

function ClassRef:setButtonVisible(aVisible)
	self._ui["Panel/Panel_open"]:setVisible(aVisible)
	self._ui["Panel/Panel_open/bg"]:setVisible(aVisible)
	self._ui["Panel/Panel_open/icon"]:setVisible(aVisible)
	self._ui["Panel/Panel_open/Text_name"]:setVisible(aVisible)
	self._num:setVisible(aVisible)
	self._tips:setVisible(aVisible)
end


return ClassRef